from django.shortcuts import render
from web import models
from web.forms.wiki import  WikiModelForm
from django.views import View
from django.urls import reverse
from django.shortcuts import redirect
from django.http import JsonResponse
from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from utils.encrypt import uid
from utils.tencent.cos import upload_file
from django.views.decorators.clickjacking import xframe_options_exempt

class WikiView(View):

    def get(self,request,project_id):
        wiki_id=request.GET.get('wiki_id')
        if not wiki_id or not wiki_id.isdecimal():
            wiki_object=None
        else:
            wiki_object=models.Wiki.objects.filter(pk=wiki_id,project=request.tracer.project).first()
        return render(request,'web/wiki.html',{'wiki_object':wiki_object})

class WikeAddView(View):
    def get(self,request,project_id):
        form=WikiModelForm(request)
        return render(request,'web/wiki_form.html',{'form':form})
    def post(self,request,project_id):
        form=WikiModelForm(request,data=request.POST)
        if form.is_valid():
            if form.instance.parent:
                form.instance.depth=form.instance.parent.depth+1
            else:
                form.instance.depth=1
            form.instance.project=request.tracer.project
            form.save()
            return redirect(reverse('web:manage:wiki',kwargs={'project_id':project_id}))
        else:
            return render(request,'web/wiki_form.html',{'form':form})

class WikiCatalogView(View):
    def get(self,request,project_id):
        data=models.Wiki.objects.filter(project=request.tracer.project).values('id','title','parent_id').order_by('depth','id')
        return JsonResponse({'data':list(data),'status':True})


class WikiEditView(View):
    '''
    知识库编辑
    '''
    def get(self,request,project_id,wiki_id):
        wiki_obj=models.Wiki.objects.filter(project=request.tracer.project,pk=wiki_id).first()
        if not wiki_obj:
            return HttpResponse('没有此知识库')
        form=WikiModelForm(request,instance=wiki_obj)
        return render(request,'web/wiki_form.html',{'form':form})

    def post(self,request,project_id,wiki_id):
        wiki_obj = models.Wiki.objects.filter(project=request.tracer.project, pk=wiki_id).first()
        if not wiki_obj:
            return HttpResponse('没有此知识库')
        form=WikiModelForm(request,instance=wiki_obj,data=request.POST)
        if form.is_valid():
            if form.instance.parent:
                form.instance.depth=form.instance.parent.depth+1
            else:
                form.instance.depth=1
            form.instance.project=request.tracer.project
            form.save()
            return redirect(reverse('web:manage:wiki',kwargs={'project_id':project_id}))
        else:
            return render(request,'web/wiki_form.html',{'form':form})


class WikiDeleteView(View):
    def get(self,request,project_id,wiki_id):
        exists=models.Wiki.objects.filter(project_id=project_id,pk=wiki_id).exists()
        if exists:
            try:
                models.Wiki.objects.filter(project_id=project_id, pk=wiki_id).delete()
                return redirect(reverse('web:manage:wiki',kwargs={'project_id':project_id}))
            except Exception as e:
                return HttpResponse('删除失败')

class WikiUploadView(View):
    '''
    markdown 上传图片 到 腾讯cos的处理
    '''
    @xframe_options_exempt
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request,*args,**kwargs)

    def post(self,request,project_id):
        result = {
            'success': 0,
            'message': None,
            'url': None
        }
        try:
            #获取文件的句柄
            image_object=request.FILES.get('editormd-image-file')
            #获取文件的后缀名
            ext=image_object.name.rsplit('.')[-1]
            #对文件名进行唯一性调整 防止覆盖 桶中的同名文件
            key='{}.{}'.format(uid(request.tracer.user.mobile_phone),ext)
            #获取桶名
            bucket=request.tracer.project.bucket
            region=request.tracer.project.region
            #把上传的文件上传到腾讯cos桶中
            img_url=upload_file(bucket,region,image_object,key)
        except Exception as e:
            print('上传文件失败')
        result['success']=1
        result['url']=img_url
        return JsonResponse(result)